import plugin from '../../lib/plugins/plugin.js';
import fs from 'node:fs';
import path from 'node:path';
import { exec } from 'node:child_process';
import schedule from 'node-schedule';

const _path = process.cwd();
const targetDir = `${_path}/plugins/miao-plugin/resources/meta-sr/character/遐蝶/imgs`;
const targetDir1 = `${_path}/plugins/miao-plugin/resources/meta-sr/character/遐蝶`;
const targetDir2 = `${_path}/plugins/miao-plugin/resources/meta-sr/character`;

export class miaoresources extends plugin {
  constructor() {
    super({
      name: '喵喵资源下载器',
      desc: '根据 JSON 文件下载并分类保存攻略和材料图片',
      event: 'message',
      priority: 50,
      rule: [
        { reg: '^#更新喵喵资源$', fnc: 'handleUpdateResources', permission: 'master' },
        { reg: '^#喵喵下载器js更新$', fnc: 'handleUpdatejs', permission: 'master' }
      ],
    });

    // Schedule automatic update every day at midnight
    schedule.scheduleJob('0 0 0 * * *', async () => {
      try {
        logger.info('开始执行自动更新插件...');
        const command = 'curl -o "./plugins/example/resourcedownloads.js" "https://gitee.com/mingdiandianzhu/data/raw/master/resourcedownloads.js"';
        await this.executeCommand(command);
        logger.info('插件自动更新成功！');
      } catch (error) {
        logger.error('自动更新插件失败:', error);
      }
    });
  }

  async handleUpdateResources(e) {
    await e.reply('开始更新喵喵资源，请稍候...（感谢  樱奈：https://gitee.com/euiko提供的资源  ）');
    
    // Create directories if they don't exist
    const dirs = [targetDir, targetDir1, targetDir2];
    for (const dir of dirs) {
      if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir, { recursive: true });
        logger.info(`创建目录: ${dir}`);
      }
    }

    const commands = [
      `curl -o "${targetDir}/cons-1.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/cons-1.webp"`,
      `curl -o "${targetDir}/cons-2.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/cons-2.webp"`,

      `curl -o "${targetDir}/cons-4.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/cons-4.webp"`,
     
      `curl -o "${targetDir}/cons-6.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/cons-6.webp"`,
      `curl -o "${targetDir}/tree-3.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/tree-3.webp"`,
      `curl -o "${targetDir}/face.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/face.webp"`,
      `curl -o "${targetDir}/preview.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/preview.webp"`,
      `curl -o "${targetDir}/splash.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/splash.webp"`,
      `curl -o "${targetDir}/talent-a.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/talent-a.webp"`,
      `curl -o "${targetDir}/talent-e.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/talent-e.webp"`,
      `curl -o "${targetDir}/talent-q.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/talent-q.webp"`,
      `curl -o "${targetDir}/talent-t.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/talent-t.webp"`,
      `curl -o "${targetDir}/talent-z.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/talent-z.webp"`,
      `curl -o "${targetDir}/tree-1.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/tree-1.webp"`,
      `curl -o "${targetDir}/tree-2.webp" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/imgs/tree-2.webp"`,

      `curl -o "${targetDir1}/data.json" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/遐蝶/data.json"`,
      `curl -o "${targetDir2}/alias.js" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/alias.js"`,
      `curl -o "${targetDir2}/data.json" "https://gh-proxy.com/https://raw.githubusercontent.com/yoimiya-kokomi/miao-plugin/master/resources/meta-sr/character/data.json"`
    ];

    let failedCommands = [...commands];
    while (failedCommands.length > 0) {
      const currentBatch = [...failedCommands];
      failedCommands = [];
      
      for (const command of currentBatch) {
        try {
          await this.executeCommand(command);
        } catch (error) {
          logger.mark(`资源下载失败，正在重试: ${command} - ${error.message}`);
          failedCommands.push(command);
        }
      }
    }
    
    await e.reply('喵喵资源更新完成！');
  }

  async handleUpdatejs(e) {
    await e.reply('开始更新本插件，请稍候...');
    const command = 'curl -o "./plugins/example/resourcedownloads.js" "https://gitee.com/mingdiandianzhu/data/raw/master/resourcedownloads.js"';
    await this.executeCommand(command);
    await e.reply('本插件更新成功！');
  }

  executeCommand(command) {
    return new Promise((resolve, reject) => {
      exec(command, (error) => {
        if (error) {
          reject(error);
        } else resolve();
      });
    });
  }
}